package com.becca.cake.service.coupon.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.becca.cake.core.excel.excelWriter.ExcelInfo;
import com.becca.cake.core.excel.excelWriter.impl.ExcelWriteHandle;
import com.becca.cake.core.exception.ServiceException;
import com.becca.cake.dao.coupon.CouponDAO;
import com.becca.cake.model.coupon.CouponExcelModel;
import com.becca.cake.model.coupon.CouponModel;
import com.becca.cake.model.coupon.CouponSaleSlipModel;
import com.becca.cake.model.system.AdminDO;
import com.becca.cake.service.coupon.ICouponService;
import com.becca.cake.util.DateUtils;
import com.becca.cake.util.JsonUtil;
import com.becca.cake.util.ShareCodeUtil;
import com.becca.cake.util.StringUtil;

/**
 * 优惠管理service
 * @copyright  尊星(上海)信息科技有限公司
 * @author hejinguo
 * @date 2016年7月1日 上午9:04:19
 */
@Service
public class CouponServiceImpl implements ICouponService {
    @Autowired
    private CouponDAO couponDAO;

    @Override
    public List<CouponModel> selectCoupon(Map<String, Object> map) throws ServiceException {
        return this.couponDAO.selectCoupon(map);
    }

    @Override
    public Long selectCouponCount(Map<String, Object> map) throws ServiceException {
        return this.couponDAO.selectCouponCount(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void insertOrUpdateCoupon(CouponModel couponModel, String isAutomatic,
                                     Integer couponCodeNumber, AdminDO adminDo)
                                                                               throws ServiceException {
        // step:1 校验
        CouponModel.validCouponIsNull(couponModel);
        // step:2 添加或修改
        if (couponModel.getId() == null) {
            couponModel.setCreatedName(adminDo.getTrueName());
            Map<String, Object> map = new HashMap<String, Object>();
            for (int i = 0; i < couponCodeNumber; i++) {
                // 手动输入优惠码的处理
                if (CouponModel.IS_AUTOMATIC_NO.equals(isAutomatic)) {
                    if (StringUtil.isEmpty(couponModel.getCouponCode())) {
                        throw new ServiceException(CouponModel.COUPON_CODE_NULL);
                    }
                    String couponCode = couponModel.getCouponCode().toUpperCase();
                    couponModel.setCouponCode(couponCode);
                    long isCouponCodeExist = this.couponDAO.isCouponCodeExist(couponModel);
                    if (isCouponCodeExist != 0) {
                        throw new ServiceException(CouponModel.COUPON_CODE_EXIST);
                    }
                }
                this.couponDAO.insertCoupon(couponModel);
                // 自动生成优惠码
                String couponCode = ShareCodeUtil.toSerialCode(couponModel.getId());
                if (CouponModel.IS_AUTOMATIC_YES.equals(isAutomatic)) {
                    map.put("couponCode", couponCode);
                    map.put("id", couponModel.getId());
                    this.couponDAO.updCouponCode(map);
                }
            }
        } else {
            if (StringUtil.isEmpty(couponModel.getCouponCode())) {
                throw new ServiceException(CouponModel.COUPON_CODE_NULL);
            }
            long isCouponCodeExist = this.couponDAO.isCouponCodeExist(couponModel);
            if (isCouponCodeExist != 0) {
                throw new ServiceException(CouponModel.COUPON_CODE_EXIST);
            }
            couponModel.setUpdatedName(adminDo.getTrueName());
            this.couponDAO.updateCoupon(couponModel);
        }
    }

    @Override
    public CouponModel queryCouponById(Integer id) throws ServiceException {
        // 1.step 校验优惠码ID是否为空
        CouponModel.validCouponIdNull(id);
        // 2.step 根据优惠码ID查询数据
        return this.couponDAO.queryCouponById(id);
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public void exportCouponsToExcel(HttpServletRequest request, HttpServletResponse response,
                                     String jsonList) throws ServiceException {
        List list = JsonUtil.returnObjectList(jsonList, CouponExcelModel.class);
        ExcelInfo info = new ExcelInfo();
        info.setColumnHeader("优惠码名称 ,优惠码 ,有效开始时间,有效结束时间");
        info.setFeilds("couponCodeName,couponCode,couponBeginDate,couponEndDate");
        info.setDatas(list);
        info.setSheetName("优惠码信息");
        info.setFileName(DateUtils.getStringToday() + "优惠码");
        ExcelWriteHandle.getInstance().writeEcxcel(info, request, response);

    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void updateActivatedCoupon(String couponIds, Byte couponType, String couponEndDate,String salesName,
                                      AdminDO adminDo) throws ServiceException {
        //step1:请求参数封装
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("isEnable", CouponModel.IS_ENABLE_YES);
        paramMap.put("couponIds", couponIds);
        paramMap.put("couponType", couponType);
        paramMap.put("couponEndDate", couponEndDate);
        paramMap.put("updatedName", adminDo.getTrueName());
        paramMap.put("salesName", salesName);
        this.couponDAO.updateActivatedCoupon(paramMap);
    }

    @Override
    public List<CouponSaleSlipModel> selectCouponSale(Map<String, Object> map)
                                                                              throws ServiceException {

        return this.couponDAO.selectCouponSale(map);
    }

    @Override
    public Long selectCouponSaleSlipCount(Map<String, Object> map) throws ServiceException {

        return this.couponDAO.selectCouponSaleSlipCount(map);
    }

    @Override
    public void deleteCouponSaleById(Integer id) throws ServiceException {
        this.couponDAO.deleteCouponSaleSlipById(id);

    }

    @Override
    public void insertOrUpdateCouponSale(CouponSaleSlipModel couponSaleSlipModel, AdminDO adminDo)
                                                                                                  throws ServiceException {
        if (couponSaleSlipModel.getId() == null) {//添加
            couponSaleSlipModel.setCreatedName(adminDo.getTrueName());
            this.couponDAO.insertCouponSaleSlip(couponSaleSlipModel);
        } else {//修改
            this.couponDAO.updateCouponSaleSlip(couponSaleSlipModel);
        }

    }

    @Override
    public CouponSaleSlipModel selectCouponSaleById(Integer couponSaleId) {
        CouponSaleSlipModel.validCouponSaleIdNull(couponSaleId);
        return this.couponDAO.selectCouponSaleById(couponSaleId);
    }

	@Override
	public List<CouponModel> selectCouponStatus(Map<String, Object> map)
			throws ServiceException
	{
		return this.couponDAO.selectCouponStatus(map);
	}

	@Override
	public Long selectCouponStatusCount(Map<String, Object> map)
			throws ServiceException
	{
		return this.couponDAO.selectCouponStatusCount(map);
	}

}
